package com.wwu.system.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wwu.system.common.security.SecurityUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 *  Mybatisplus字段自动填充功能
 *  填充创建人、创建时间、修改人和修改时间
 * @author 一蓑烟雨
 * @date 2021-12-01 19:48
 * @version 1.0.0
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //判断是否有createTime属性的Set方法
        boolean hasSetter1 = metaObject.hasSetter("createTime");
        if(hasSetter1){
            this.setFieldValByName("createTime", LocalDateTime.now(),metaObject);
        }

        //判断是否有modifyTime属性的Set方法
        boolean hasSetter2 = metaObject.hasSetter("modifyTime");
        if(hasSetter2){
            this.setFieldValByName("modifyTime", LocalDateTime.now(),metaObject);
        }

        //判断是否有creator属性的Set方法
        boolean hasSetter3 = metaObject.hasSetter("creator");
        if(hasSetter1){
            this.setFieldValByName("creator", SecurityUtil.getCurrUserName(),metaObject);
        }

        //判断是否有modifier属性的Set方法
        boolean hasSetter4 = metaObject.hasSetter("modifier");
        if(hasSetter2){
            this.setFieldValByName("modifier", SecurityUtil.getCurrUserName(),metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //判断是modifyTime属性的Set方法
        Object val1 = getFieldValByName("modifyTime", metaObject);
        if(val1==null){
            this.setFieldValByName("modifyTime",LocalDateTime.now(),metaObject);
        }

        //判断是modifier属性的Set方法
        Object val2 = getFieldValByName("modifier", metaObject);
        if(val2==null){
            this.setFieldValByName("modifier", SecurityUtil.getCurrUserName(),metaObject);
        }
    }
}
